// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: Markus Gutschke

#include <stdlib.h>
#include <string.h>

#include "check.h"
#include "json.h"
#include "http.h"
#include "multipart.h"
#include "register_printer.h"
#include "stringprintf.h"


struct JSON *registerPrinter(const char *url, const char *printername,
                             const char *proxyname, const char *description,
                             const char *capabilities, const char *defaults,
                             const char *mime_type) {
  // Construct "register" URL
  char *api = stringPrintf(NULL, "%s/register", url);

  // Send the registration request
  struct MultiPart multipart;
  initMultiPart(&multipart);
  addToMultiPart(&multipart, "printer", printername, -1, "text/plain");
  addToMultiPart(&multipart, "proxy", proxyname, -1, "text/plain");
  addToMultiPart(&multipart, "status", "online", -1, "text/plain");
  addToMultiPart(&multipart, "description", description, -1, "text/plain");
  addToMultiPart(&multipart, "capsHash", "", -1,  "text/plain");
  addToMultiPart(&multipart, "capabilities", capabilities, -1, mime_type);
  addToMultiPart(&multipart, "defaults", defaults, -1, mime_type);
  const char *body = POST(api, NULL, &multipart, M_MULTIPART);
  free(api);
  destroyMultiPart(&multipart);

  // Parse response
  struct JSON *json = newJSON(body);
  free((void *)body);

  // Verify that the registration was successful
  check(json->type == J_OBJECT);
  const struct JSON *success;
  check((success = (const struct JSON *)
         getFromHashMap(&json->obj, "success")) &&
        success->type == J_TRUE);

  return json;
}
